const axios = require('axios')
const log4js = require('../utils/log4j')
const _ = require('lodash')
const { method } = require('lodash')
const config = require('../config/index')
class GetTables {
  constructor() {
    axios.defaults.baseURL = 'https://api.huoban.com'
    axios.defaults.headers.common['Authorization'] = config.token
    /** 基础配置参数 */
    this.BASE_URL = {
      TIME: config.TIME,
      Q: config.Q,
      Y: config.Y,
      B: config.B,
      QF: [],
      YF: [],
      BF: [],
      YL: [],
      QL: [],
      BL: [],
      YJ: {},
      QJ: {},
      BJ: {},
    }
    /** 所有分区下的用户ID */
    this.USER_ID = {}
    /** 所有分区ID */
    this.Group_Id = {}
    /** 请求数据头部参数 */
    this.headers = {
      'x-huoban-return-fields': '',
      'x-huoban-monitor-tag': 'item_list',
    }
    this.WHERE = {
      method: 'post',
      url: '',
      data: {
        where: {},
        offset: 0,
        limit: 20,
      },
      headers: this.headers,
    }
  }
  async init() {
    /** 初始化分类id */
    await this.getInitFileId()
    /** 初始化分区ID */
    await this.getTablesId()
    /** 初始化获取用户ID */
    await this.getUserId()
  }
  /** 获取分区ID */
  getTablesId = async () => {
    let { data } = await axios.get('/v2/spaces/joined?type=all')
    const arr = { Y: '', Q: '', B: '' }
    data.map((item) => {
      if (item.name == 'Young') {
        arr.Y = item.space_id
      } else if (item.name == '077') {
        arr.Q = item.space_id
      } else if (item.name == 'yxb') {
        arr.B = item.space_id
      }
    })
    this.Group_Id = arr
  }
  /** 获取获取分区下的所有表格:名称+创建时间+ID+表格ID */
  getTables = async () => {
    let arr = this.Group_Id
    console.log(this.Group_Id)
    let request = []
    for (let key in arr) {
      request.push(axios.get(`/v2/space/${arr[key]}`))
    }
    let { ...data } = await axios.all(request)
    let time = []
    for (let key in data) {
      let i = data[key]['data']
      time.push({
        name: i['name'],
        created_on: i['created_on'],
        space_id: i['space_id'],
        table_ids: i['table_ids '],
      })
    }
    return time
  }
  /** 获取表格下的排序的ID,如操作时间:10000,操作人员:1000001 */
  async getFieldId(tabid, fli) {
    const { data } = await axios.post(`/v2/item/table/${tabid}/get_range`, {
      filter: { and: [] },
    })
    let fs = []
    let fsObj = {}
    data.fields.map((item) => {
      if (
        item.name !== '支付宝姓名' &&
        item.name !== 'UID' &&
        item.name !== '公众号UID/支付宝编号'
      ) {
        fs.push(item.field_id)
        fsObj[item.name] = item.field_id
      }
    })
    /** 拼接条件字段 */
    let list = [
      'filtered',
      'total',
      {
        items: [
          [
            '*',
            {
              updated_by: ['user_id', 'name'],
            },
            {
              '@': {
                fields: fs,
              },
            },
          ],
        ],
      },
    ]
    /** 赋值给全局变量 */
    if (fli == 'Y') {
      this.BASE_URL.YF = list
      this.BASE_URL.YL = fs
      this.BASE_URL.YJ = fsObj
    } else if (fli == 'Q') {
      this.BASE_URL.QF = list
      this.BASE_URL.QL = fs
      this.BASE_URL.QJ = fsObj
    } else if (fli == 'B') {
      this.BASE_URL.BF = list
      this.BASE_URL.BL = fs
      this.BASE_URL.BJ = fsObj
    }
    return
  }
  /** 执行获取分类ID,避免重复获取 */
  async getInitFileId() {
    for (const key in this.BASE_URL) {
      if (key == 'Y' || key == 'Q' || key == 'B') {
        await this.getFieldId(this.BASE_URL[key], key)
      }
    }
  }
  /** 获取所有分区下的用户id,并且赋值给全局变量方便调用 */
  getUserId = async () => {
    let arr = this.Group_Id
    let userArray = []
    for (let key in arr) {
      userArray.push(axios.get(`/v2/members_and_groups/space/${arr[key]}`))
    }
    const data = await axios.all(userArray)
    let a = {}
    data.map((item) => {
      for (let k in item.data['space_members']) {
        a[item.data['space_members'][k]['member']['name']] =
          item.data['space_members'][k]['member']['user_id']
      }
    })
    this.USER_ID = a
  }
  /** 判断设置条件
   * @param {String} name:店铺名
   * @param {String} name:用户名
   * @param {String} name:分组 Y Q B
   */
  initWher = async (name, user, group) => {
    let url = '',
      fields = [],
      field = 0,
      userField = 0
    if (group == 'Y') {
      this.headers['x-huoban-return-fields'] = this.BASE_URL.YF
      url = `/v2/item/table/${this.BASE_URL.Y}/find`
      fields = [this.BASE_URL.YJ['店铺名']]
      field = this.BASE_URL.YJ['时间日期']
      userField = this.BASE_URL.YJ['操作人员']
    } else if (group == 'Q') {
      this.headers['x-huoban-return-fields'] = this.BASE_URL.QF
      url = `/v2/item/table/${this.BASE_URL.Q}/find`
      fields = [this.BASE_URL.QJ['店铺名']]
      field = this.BASE_URL.QJ['时间日期']
      userField = this.BASE_URL.QJ['操作人员']
    } else if (group == 'B') {
      this.headers['x-huoban-return-fields'] = this.BASE_URL.BF
      url = `/v2/item/table/${this.BASE_URL.B}/find`
      fields = [this.BASE_URL.BJ['店铺名']]
      field = this.BASE_URL.BJ['时间日期']
      userField = this.BASE_URL.BJ['操作人员']
    }
    /** 当只传递了店铺名和分组时 */
    if (name !== '' && user == '') {
      this.WHERE.url = url
      this.WHERE.data['search'] = {
        fields: fields,
        keywords: [name],
      }
      this.WHERE.data['where'] = {
        and: [{ field: field, query: { eq: this.BASE_URL.TIME } }],
      }
    }
    /** 当传递了店铺名 + 用户时 */
    if (name !== '' && user !== '') {
      this.WHERE.url = url
      this.WHERE.data['search'] = {
        fields: fields,
        keywords: [name],
      }
      this.WHERE.data['where'] = {
        and: [
          { field: field, query: { eq: this.BASE_URL.TIME } },
          { field: userField, query: { in: this.USER_ID[user] } },
        ],
      }
    }
    /** 当只传递了用户名时 */
    if (name == '' && user !== '') {
      this.WHERE.url = url
      this.WHERE.data['where'] = {
        and: [
          { field: field, query: { eq: this.BASE_URL.TIME } },
          { field: userField, query: { in: this.USER_ID[user] } },
        ],
      }
    }
  }
  /** 根据分组+店铺名获取数量或数据*/
  getDataCount = async (name, group, count) => {
    try {
      let res = ''
      await this.initWher(name, '', group)
      if (count !== undefined) {
        this.WHERE.data.offset = count * 20
      }
      const { data } = await axios(this.WHERE)
      if (count !== undefined) {
        res = data.items
      } else {
        res = data.filtered
      }
      return res
    } catch (error) {
      log4js.error(error.stack)
      return {}
    }
  }
  /** 根据店铺名+分区导出数据 */
  getGroupNameData = async (name, group) => {
    try {
      const T = await this.getDataCount(name, group)
      const count = Math.ceil(T / 20)
      let array = []
      for (let i = 0; i < count; i++) {
        array.push(this.getDataCount(name, group, i))
      }
      const res = await Promise.all(array)
      let objArray = []
      let dataArray = []
      let arty = res.flat()
      arty.map((item) => {
        objArray.push(item.fields)
      })
      objArray.map((item) => {
        let j = {}
        item.map((key) => {
          const val = key.field_id
          let name = ''
          if (group == 'Y') {
            name = this.findKey(this.BASE_URL.YJ, val)
          } else if (group == 'B') {
            name = this.findKey(this.BASE_URL.BJ, val)
          } else if (group == 'Q') {
            name = this.findKey(this.BASE_URL.QJ, val)
          }
          if (name !== undefined)
            j[name] = key['values'][0].value || key['values'][0].name
        })
        dataArray.push(j)
      })
      return dataArray
    } catch (error) {
      log4js.error(error.stack)
    }
  }
  /** 根据店铺名+用户+分组获取数据 */
  getUserDataCount = async (name, user, group, count) => {
    try {
      await this.initWher(name, user, group)
      if (count !== undefined) {
        this.WHERE.data.offset = count * 20
      } else {
        this.WHERE.data.offset = 0
      }
      const { data } = await axios(this.WHERE)
      if (count !== undefined) {
        return data.items
      } else {
        return data.filtered
      }
    } catch (error) {
      log4js.error(error.stack)
    }
  }
  /** 根据名称+分组获取数据 */
  getUserData = async (user, group, count) => {
    try {
      await this.initWher('', user, group)
      if (count !== undefined) {
        this.WHERE.data.offset = count * 20
      }
      const { data } = await axios(this.WHERE)
      return { res: data.items, c: data.filtered }
    } catch (error) {
      console.log(error)
    }
  }
  /** 根据人员+店铺名获取数据+分区获取数据*/
  getTableCountData = async (name, user, group) => {
    try {
      const c = await this.getUserDataCount(name, user, group)
      const count = Math.ceil(c / 20)
      const allAxios = []
      let arrar = []
      for (let i = 0; i < count; i++) {
        allAxios.push(this.getUserDataCount(name, user, group, i))
      }
      const res = await Promise.all(allAxios)
      arrar = res.flat()
      let objArray = []
      let dataArray = []
      arrar.map((item) => {
        objArray.push(item.fields)
      })
      objArray.map((item) => {
        let j = {}
        item.map((key) => {
          const val = key.field_id
          let name = ''
          if (group == 'Y') {
            name = this.findKey(this.BASE_URL.YJ, val)
          } else if (group == 'B') {
            name = this.findKey(this.BASE_URL.BJ, val)
          } else if (group == 'Q') {
            name = this.findKey(this.BASE_URL.QJ, val)
          }
          if (name !== undefined)
            j[name] = key['values'][0].value || key['values'][0].name
        })
        dataArray.push(j)
      })
      return dataArray
    } catch (error) {
      log4js.error(error.stack)
    }
  }
  /** 通过value取key */
  findKey(data, value, compare = (a, b) => a === b) {
    return Object.keys(data).find((k) => compare(data[k], value))
  }
  /** 获取全部分区下的最近操作动态 */
  getDynamic = async () => {
    let tabId = [
      Number(this.Group_Id.Q),
      Number(this.Group_Id.B),
      Number(this.Group_Id.Y),
    ]
    let allAxios = []
    tabId.map((item) => {
      allAxios.push(axios.get(`/v2/streams/space/${item}`))
    })
    const resultArray = await axios.all(allAxios)
    let dataArray = []
    resultArray.map((item) => {
      const { data } = item
      dataArray.push(data)
    })
    dataArray = dataArray.flat()
    let result = {}
    _.mapKeys(dataArray, function (value, key) {
      result[key] = value.title
    })
    return result
  }
  /** 累加计数 */
  getRepeatNum(arr) {
    return arr.reduce(function (prev, next) {
      prev[next] = prev[next] + 1 || 1
      return prev
    }, {})
  }
  /** 根据人员，分区查询店铺统计数量 */
  getDeptNameCount = async (user, group) => {
    try {
      const { c } = await this.getUserData(user, group)
      const count = Math.ceil(c / 20)
      let allAxios = []
      let arrar = []
      let deptId = ''
      if (group == 'B') {
        deptId = [this.BASE_URL.BJ['店铺名']]
      } else if (group == 'Q') {
        deptId = [this.BASE_URL.QJ['店铺名']]
      } else if (group == 'Y') {
        deptId = [this.BASE_URL.YJ['店铺名']]
      }
      for (let i = 0; i < count; i++) {
        allAxios.push(this.getUserData(user, group, i))
      }
      const res = await Promise.all(allAxios)
      res.map((item) => {
        item.res.map((key) => {
          key['fields'].map((value) => {
            if (value['field_id'] == deptId) {
              let deptname = value['values'][0]['name']
              arrar.push(deptname)
            }
          })
        })
      })
      return this.getRepeatNum(arrar)
    } catch (error) {
      log4js.error(error.stack)
    }
  }
  /** 根据姓名+分区导出表格数据 */
  getUserAndGroupAll = async (user, group) => {
    try {
      const { c } = await this.getUserData(user, group)
      const count = Math.ceil(c / 20)
      let allAxios = []
      let arrar = []
      let deptId = ''
      if (group == 'B') {
        deptId = [this.BASE_URL.BJ['店铺名']]
      } else if (group == 'Q') {
        deptId = [this.BASE_URL.QJ['店铺名']]
      } else if (group == 'Y') {
        deptId = [this.BASE_URL.YJ['店铺名']]
      }
      for (let i = 0; i < count; i++) {
        allAxios.push(this.getUserData(user, group, i))
      }
      const res = await Promise.all(allAxios)
      let ALLarr = []
      res.map((item) => {
        item.res.map((key) => {
          ALLarr.push(key['fields'])
        })
      })
      let DeptArray = {}
      ALLarr.map((key) => {
        let j = {}
        let deptName = ''
        key.map((item) => {
          const val = item['field_id']
          let name = ''
          if (group == 'Y') {
            name = this.findKey(this.BASE_URL.YJ, val)
          } else if (group == 'B') {
            name = this.findKey(this.BASE_URL.BJ, val)
          } else if (group == 'Q') {
            name = this.findKey(this.BASE_URL.QJ, val)
          }
          if (name !== undefined) {
            j[name] = item['values'][0].value || item['values'][0].name
          }
          if (name == '店铺名') {
            deptName = item['values'][0].value || item['values'][0].name
          }
        })
        if (DeptArray[deptName] != undefined) {
          DeptArray[deptName].push(j)
        } else {
          DeptArray[deptName] = [j]
        }
      })
      return DeptArray
    } catch (error) {
      log4js.error(error.stack)
    }
  }
}
module.exports = new GetTables()
